import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/operational_statistics/response/month_activity_data.dart';
import 'package:ls_work/operational_statistics/view_model/operational_statistics_view_model.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/util/ext_utils.dart';

import '../../widgets/static_chat_bar_widget.dart';
import '../response/month_into_out_data.dart';

class OperationalStatisticsPage extends BaseStatefulMvvmWidget {
  @override
  State<StatefulWidget> createState() => _OperationalStatisticsState();
}

class _OperationalStatisticsState extends BaseMvvmRefreshState<
    OperationalStatisticsViewModel, OperationalStatisticsPage> {
  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text('运营统计'),
      ),
      body: loadingContentWidget,
    );
  }

  Widget titleWidget(String title) {
    return Row(
      children: [
        Container(
          height: 20,
          width: 4,
          color: Colors.blue,
        ),
        SizedBox(
          width: 5,
        ),
        CommonText(title)
      ],
    );
  }

  Widget contentItem(String title, String value, String unit) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        CommonText(title),
        SizedBox(
          height: 8,
        ),
        Text.rich(TextSpan(
            text: value,
            style: TextStyle(
                color: Colours.text_dark,
                fontSize: 19,
                fontWeight: FontWeight.bold),
            children: [
              TextSpan(
                  text: unit,
                  style: TextStyle(fontSize: 14, color: Colours.gray_99))
            ]))
      ],
    );
  }

  @override
  Widget createScrollWidget() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Column(
        children: [
          Column(
            children: [
              titleWidget('运营情况'),
              Gaps.dividerLine,
              Row(
                children: [
                  contentItem('总床位数', "${viewModel.totalBedNum}", '人')
                      .setWeight(1),
                  contentItem('总入住数', "${viewModel.totalIntoNum}", '人')
                      .setWeight(1),
                  contentItem('入住率', "${viewModel.intoPercent??""}", '%')
                      .setWeight(1),
                ],
              ),
              Row(
                children: [
                  contentItem('今日入住', "${viewModel.todayInto}", '')
                      .setWeight(1),
                  contentItem('今日退住', "${viewModel.todayOut}", '').setWeight(1),
                  contentItem('本月入住', "${viewModel.monthInto}", '')
                      .setWeight(1),
                  contentItem('本月退住', "${viewModel.monthOut}", '').setWeight(1),
                ],
              ),
              Row(
                children: [
                  contentItem('本月服务单数', "${viewModel.monthOrderNum}", '')
                      .setWeight(1),
                  contentItem('本月照护次数', "${viewModel.monthNurseTimes}", '')
                      .setWeight(1),
                  contentItem('本月告警次数', "${viewModel.monthWarningTimes}", '')
                      .setWeight(1),
                ],
              )
            ].insertWidget(SizedBox(
              height: 14,
            )),
          ).addToContainer(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: 8.borderRadius,
              ),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
          if (viewModel.monthInOutChart != null) ...[
            SizedBox(
              height: 15,
            ),
            Column(
              children: [
                titleWidget('近6个月入退住统计'),
                Gaps.dividerLine,
                MonthIntoOutChart(viewModel.monthInOutChart!)
              ].insertWidget(SizedBox(
                height: 12,
              )),
            ).addToContainer(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: 8.borderRadius,
                ),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
          ],
          if (viewModel.monthActivityChart != null) ...[
            SizedBox(
              height: 15,
            ),
            Column(
              children: [
                titleWidget('近6个月活动举办数统计'),
                Gaps.dividerLine,
                MonthActivityJoinChart(viewModel.monthActivityChart!)
              ].insertWidget(SizedBox(
                height: 12,
              )),
            ).addToContainer(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: 8.borderRadius,
                ),
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
          ]
        ],
      ),
    );
  }

  @override
  OperationalStatisticsViewModel createViewModel() {
    return OperationalStatisticsViewModel(context);
  }
}

class MonthIntoOutChart extends StatelessWidget {
  MonthIntoOutData info;

  List<BarData> barData = [];

  MonthIntoOutChart(this.info) {}

  var colors = [
    Color(0xff8AC9FD),
    Color(0xffFF7C8A),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Container(
              width: 15,
              height: 15,
              color: colors[0],
            ),
            SizedBox(
              width: 4,
            ),
            CommonText('入住'),
            SizedBox(
              width: 20,
            ),
            Container(
              width: 15,
              height: 15,
              color: colors[1],
            ),
            SizedBox(
              width: 4,
            ),
            CommonText('退住'),
          ],
        ),
        AspectRatio(
          aspectRatio: 1.66,
          child: Padding(
            padding: const EdgeInsets.only(top: 16),
            child: LayoutBuilder(
              builder: (context, constraints) {
                final barsSpace = 20.0;
                final barsWidth = 30.0;
                return BarChart(
                  BarChartData(
                    alignment: BarChartAlignment.center,
                    barTouchData: BarTouchData(
                      enabled: true,
                      touchTooltipData: BarTouchTooltipData(getTooltipItem:
                          (BarChartGroupData group, int groupIndex,
                              BarChartRodData rod, int rodIndex) {
                        var item = info.intoList![groupIndex];
                        var outItem = info.outList![groupIndex];
                        return BarTooltipItem(
                            "${item.month}\n入住：${item.number}\n退住：${outItem.number}",
                            TextStyle(color: Colors.white));
                      }),
                    ),
                    extraLinesData: ExtraLinesData(horizontalLines: [
                      HorizontalLine(y: 0, color: Colors.grey)
                    ], verticalLines: [
                      VerticalLine(x: 0, color: Colors.grey)
                    ]),
                    titlesData: FlTitlesData(
                      show: true,
                      bottomTitles: AxisTitles(
                        sideTitles: SideTitles(
                          showTitles: true,
                          reservedSize: 28,
                          getTitlesWidget: bottomTitles,
                        ),
                      ),
                      leftTitles: AxisTitles(
                        sideTitles: SideTitles(
                          showTitles: true,
                          reservedSize: 40,
                          getTitlesWidget: leftTitles,
                        ),
                      ),
                      topTitles: const AxisTitles(
                        sideTitles: SideTitles(showTitles: false),
                      ),
                      rightTitles: const AxisTitles(
                        sideTitles: SideTitles(showTitles: false),
                      ),
                    ),
                    gridData: FlGridData(
                      show: true,
                      // checkToShowHorizontalLine: (value) => value % 10 == 0,
                      getDrawingHorizontalLine: (value) => FlLine(
                        color: Colours.app_main.withOpacity(0.4),
                        strokeWidth: 1,
                      ),
                      drawVerticalLine: false,
                    ),
                    borderData: FlBorderData(
                      show: false,
                    ),
                    groupsSpace: barsSpace,
                    barGroups: getData(barsWidth, barsSpace),
                  ),
                );
              },
            ),
          ),
        )
      ],
    );
  }

  List<BarChartGroupData> getData(double barsWidth, double barsSpace) {
    return List.generate((info.intoList ?? []).length, (index) {
      return BarChartGroupData(x: index, barsSpace: barsSpace, barRods: [
        BarChartRodData(
          toY: ((info.intoList![index].number ?? 0) +
                  (info.outList![index].number ?? 0))
              .toDouble(),
          rodStackItems: [
            BarChartRodStackItem(
                0, (info.intoList![index].number ?? 0).toDouble(), colors[0]),
            BarChartRodStackItem(
                (info.intoList![index].number ?? 0).toDouble(),
                ((info.intoList![index].number ?? 0) +
                        (info.outList![index].number ?? 0))
                    .toDouble(),
                colors[1]),
          ],
          borderRadius: BorderRadius.zero,
          width: barsWidth,
        )
      ]);
    });
  }

  Widget bottomTitles(double value, TitleMeta meta) {
    const style = TextStyle(fontSize: 14);
    String text =
        "${((info.intoList ?? [])[value.toInt()].month ?? "").split("-").last}月";
    return SideTitleWidget(
      axisSide: meta.axisSide,
      child: Text(text, style: style),
    );
  }

  Widget leftTitles(double value, TitleMeta meta) {
    if (value == meta.max) {
      return Container();
    }
    const style = TextStyle(
      fontSize: 14,
    );
    return SideTitleWidget(
      axisSide: meta.axisSide,
      child: Text(
        meta.formattedValue,
        style: style,
      ),
    );
  }
}

class MonthActivityJoinChart extends StatelessWidget {
  MonthActivityData info;

  List<BarData> barData = [];

  MonthActivityJoinChart(this.info) {}

  var colors = [
    Color(0xff84E6A6),
    Color(0xffFF7C8A),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        AspectRatio(
          aspectRatio: 1.66,
          child: Padding(
            padding: const EdgeInsets.only(top: 16),
            child: LayoutBuilder(
              builder: (context, constraints) {
                final barsSpace = 10.0;
                final barsWidth = 10.0;
                return BarChart(
                  BarChartData(
                    alignment: BarChartAlignment.center,
                    barTouchData: BarTouchData(
                      enabled: true,
                      touchTooltipData: BarTouchTooltipData(getTooltipItem:
                          (BarChartGroupData group, int groupIndex,
                              BarChartRodData rod, int rodIndex) {
                        var item = info.customerJoinList![groupIndex];
                        return BarTooltipItem("${item.month}：${item.number}",
                            TextStyle(color: Colors.white));
                      }),
                    ),
                    extraLinesData: ExtraLinesData(horizontalLines: [HorizontalLine(y: 0,color: Colors.grey)]),
                    titlesData: FlTitlesData(
                      show: true,
                      bottomTitles: AxisTitles(
                        sideTitles: SideTitles(
                          showTitles: true,
                          reservedSize: 28,
                          getTitlesWidget: bottomTitles,
                        ),
                      ),
                      leftTitles: AxisTitles(
                        sideTitles: SideTitles(
                          showTitles: true,
                          reservedSize: 40,
                          getTitlesWidget: leftTitles,
                        ),
                      ),
                      topTitles: const AxisTitles(
                        sideTitles: SideTitles(showTitles: false),
                      ),
                      rightTitles: const AxisTitles(
                        sideTitles: SideTitles(showTitles: false),
                      ),
                    ),
                    gridData: FlGridData(
                      show: true,
                      // checkToShowHorizontalLine: (value) => value % 10 == 0,
                      getDrawingHorizontalLine: (value) => FlLine(
                        color: Colours.app_main.withOpacity(0.4),
                        strokeWidth: 1,
                      ),
                      drawVerticalLine: false,
                    ),
                    borderData: FlBorderData(
                      show: false,
                    ),
                    groupsSpace: barsSpace,
                    barGroups: getData(barsWidth, barsSpace),
                  ),
                );
              },
            ),
          ),
        )
      ],
    );
  }

  List<BarChartGroupData> getData(double barsWidth, double barsSpace) {
    return List.generate((info.customerJoinList ?? []).length, (index) {
      return BarChartGroupData(x: index, barsSpace: barsSpace, barRods: [
        BarChartRodData(
          toY: ((info.customerJoinList![index].number ?? 0)).toDouble(),
          rodStackItems: [
            BarChartRodStackItem(
                0,
                (info.customerJoinList![index].number ?? 0).toDouble(),
                colors[0]),
          ],
          borderRadius: BorderRadius.zero,
          width: barsWidth,
        )
      ]);
    });
  }

  Widget bottomTitles(double value, TitleMeta meta) {
    const style = TextStyle(fontSize: 14);
    String text =
        "${((info.customerJoinList ?? [])[value.toInt()].month ?? "").split("-").last}月";
    return SideTitleWidget(
      angle: pi / 4,
      axisSide: meta.axisSide,
      child: Text(text, style: style),
    );
  }

  Widget leftTitles(double value, TitleMeta meta) {
    if (value == meta.max) {
      return Container();
    }
    const style = TextStyle(
      fontSize: 14,
    );
    return SideTitleWidget(
      axisSide: meta.axisSide,
      child: Text(
        meta.formattedValue,
        style: style,
      ),
    );
  }
}
